import React, { useState } from 'react'
import NavBar from '../../components/NavBar'
import styles from './index.module.scss'
import Input from '../../components/Input/index'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useDispatch } from 'react-redux'
import { loginAsync, sendCodeAsync } from '../../store/reducer/index'
import { Toast } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'

export default function Login() {
  const navigate = useNavigate()
  const [timer, setTimer] = useState(0)
  //使用redux
  const dispatch = useDispatch()
  //发送验证码请求，并处理
  const onExtraClick = async () => {
    if (timer > 0) return
    const mobile = formik.values.mobile

    //对输入的值验证
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      formik.setTouched({
        mobile: true,
      })
      return
    }
    try {
      await dispatch(sendCodeAsync(mobile))
      Toast.show({
        icon: 'success',
        content: '获取验证码成功',
        duration: 3000,
      })
      //开启倒计时
      setTimer(60)
      let timeId = setInterval(() => {
        setTimer((timer) => {
          if (timer === 1) {
            clearInterval(timeId)
          }
          return timer - 1
        })
      }, 1000)
    } catch (err) {
      Toast.show({
        icon: 'fail',
        content: '发送过于频繁',
      })
    }
  }
  //使用formik处理表单
  const formik = useFormik({
    initialValues: {
      mobile: '13911111111',
      code: '246810',
    },
    onSubmit: async (values) => {
      await dispatch(loginAsync(values))
      Toast.show({
        icon: 'success',
        content: '登录成功',
      })
      navigate('/layout')
    },
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('手机号不能为空')
        .matches(/^1[3-9]\d{9}$/, '手机号格式错误'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/^\d{6}$/, '验证码格式错误'),
    }),
  })
  //解构从表单获取到的值和formik的方法
  const {
    values: { mobile, code },
    handleChange,
    handleSubmit,
    handleBlur,
  } = formik

  return (
    <div className={styles.root}>
      {/* 标题 */}
      <NavBar extra='右侧'>登录</NavBar>
      {/* 内容 */}
      <div className='content'>
        <h3>短信登录</h3>
        <form onSubmit={handleSubmit}>
          {/* 手机号输入框 */}
          <div className='input-item'>
            <Input
              placeholder='请输入手机号'
              value={mobile}
              name='mobile'
              autoComplete='off'
              onChange={handleChange}
              onBlur={handleBlur}
              maxLength={11}
            ></Input>
            {formik.touched.mobile && formik.errors.mobile ? (
              <div className='validate'>{formik.errors.mobile}</div>
            ) : null}
          </div>
          {/*  */}
          {/* 短信验证码输入框 */}
          <div className='input-item'>
            <Input
              placeholder='请输入验证码'
              extra={timer === 0 ? '获取验证码' : `${timer}秒后获取`}
              onExtraClick={onExtraClick}
              value={code}
              name='code'
              autoComplete='off'
              onChange={handleChange}
              onBlur={handleBlur}
              maxLength={6}
            ></Input>
            {formik.touched.code && formik.errors.code ? (
              <div className='validate'>{formik.errors.code}</div>
            ) : null}
          </div>
          <button type='submit' className='login-btn'>
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
